<!--库详情页组件-->
<template>
  <div class="dataList" id="dataList">
    <div class="dataList-content">
      <!--表单页面-->
      <div class="content-form">
        <el-form :model="search" ref="searchRef" class="form-body" :inline="true">
          <el-form-item class="body-item" label="姓名：" prop="userName" v-if="libraryTypeId === 'talentPool'">
            <el-input v-model="search.userName" placeholder="请输入姓名" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item class="body-item" label="标题：" prop="title" v-if="libraryTypeId !== 'talentPool'">
            <el-input v-model="search.title" placeholder="请输入标题" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item class="body-item" label="公司名称：" prop="companyName">
            <el-input v-model="search.companyName" placeholder="请输入公司名称" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item class="body-item">
            <el-button @click="resetSearchForm">重置</el-button>
            <el-button type="primary" @click="prefectureInquire">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--操作按钮-->
      <div class="content-form-btn">
        <!--分公司录入人录入展示-->
        <el-button v-if="newState()" type="primary" icon="Plus" @click="addData" plain>新增</el-button>
        <el-button type="warning" icon="Download" plain @click="derivedData">导出</el-button>
        <!--分公司录入人录入展示-->
        <template v-if="newState()">
          <file-upload
            ref="rectifyAndRef"
            class="content-form-upload"
            :isShowTip="false"
            :listOfFiles="false"
            :fileTypes="fileUploadType"
            @handleUploadRequest="handleUploadRequest"
          >
            <template #upload>
              <el-button type="info" icon="Upload" plain>导入</el-button>
            </template>
          </file-upload>
          <el-button link icon="Download" type="primary" @click="templateDownload">导入模版下载</el-button>
        </template>
      </div>
      <!--表格页面-->
      <div class="content-table">
        <div class="table-body">
          <el-table
            ref="multipleTableRef"
            v-loading="loading"
            :data="dataList"
            border
            style="width: 100%"
            class-name="body-form"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              label="序号"
              width="70"
              align="center"
              type="index"
              :index="(search.pageNum - 1) * search.pageSize + 1"
            />
            <el-table-column
              v-for="(item, index) in tableColumnHead(libraryTypeId)"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :min-width="item.width"
              align="center"
            >
              <template #default="scope">
                <span v-if="item.formatter">{{ item.formatter(scope.row) }}</span>
                <span v-if="item.formatterStatus">{{ item.formatterStatus(scope.row) }}</span>
                <span v-if="item.formatterFile">{{ item.formatterFile(scope.row) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="200">
              <template #default="{ row }">
                <!-- 只有分公司录入人录入  并且是 草稿(不返回currentNode为草稿状态)/拟稿状态DRAFT 才可以编辑 -->
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="editData(row, 'edit')"
                  v-if="hasRole('CITY_ENTERED_BY') && !row.currentNode"
                >
                  编辑
                </el-button>
                <!-- 查看/处理 按钮 -->
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="editData(row, viewProcessing(row) === '查看' ? 'view' : 'handle')"
                  v-else
                >
                  {{ viewProcessing(row) }}
                </el-button>
                <el-button link type="primary" icon="View" @click="casePreview(row)" v-if="libraryTypeId === 'case'"
                  >预览</el-button
                >
                <!-- 当角色为分公司录入人录入 状态为 草稿/拟稿/已结束 才可以删除工单 -->
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="libraryDelete(row)"
                  v-if="hasRole('CITY_ENTERED_BY') && (!row.currentNode || deleteNodeList.includes(row.currentNode))"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-page">
          <pagination
            v-show="total > 0"
            v-model:page="search.pageNum"
            v-model:limit="search.pageSize"
            :total="total"
            @pagination="prefectureInquire"
          />
        </div>
      </div>
      <!--人员录入弹窗-->
      <personage-dialog
        ref="personageRef"
        :disabled="disabledDialog"
        :editInformation="editInformation"
        :audit-status="auditStatus"
        :id="messageId"
        @informationSubmit="informationSubmit"
        @informationSave="informationSave"
        @submitForReview="submitForReview"
      />
      <!--视频库-教案库-案例库-文献库 弹窗-->
      <other-library-dialog
        ref="otherLibraryRef"
        :disabled="disabledDialog"
        :editInformation="editInformation"
        :library-type-id="libraryTypeId"
        :audit-status="auditStatus"
        @informationSubmit="informationSubmit"
        @informationSave="informationSave"
        @submitForReview="submitForReview"
      />
      <!--案例库预览弹窗-->
      <detailedContentDialog ref="contentDialogRef" :descriptionList="editInformation" />
    </div>
  </div>
</template>
<script setup>
import personageDialog from "@/components/Dialog/personageDialog/index.vue";
import otherLibraryDialog from "@/components/Dialog/otherLibraryDialog/index.vue";
import { tableColumnHead, exportTemplateName } from "@/utils/assetsLibrary";
import { ref, reactive, onMounted } from "vue";
import { downloadTemplate, getDetail, saveAndSubmit } from "@/api/navigationLecture";
import {
  libraryList,
  removeLibrary,
  renewalLibrary,
  reviewSubmit,
  passExamination,
  auditReturn,
  importTemplate,
  exportTemplate,
} from "@/api/navigationLecture";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { fileBlobDownload } from "@/utils/fileDownload";
import detailedContentDialog from "@/components/Dialog/detailedContentDialog";
const userStore = useUserStore();
const props = defineProps({
  // 库种类型id
  libraryTypeId: {
    type: String,
    default: "",
  },
});
const { proxy } = getCurrentInstance();
const searchRef = ref(); // 首页表单ref
const total = ref(0); //模拟数据-总页数
const data = reactive({
  //基本信息表单
  search: {
    pageNum: 1,
    pageSize: 10,
    userName: "", //姓名
    title: "", // 标题
    companyName: "", //公司名称
  },
});
const { search } = toRefs(data); // 搜索表单
const multipleTableRef = ref(); // 表格ref
const loading = ref(true); // 首页列表加载状态
const dataList = ref([]); // 首页列表数据
const personageRef = ref(); // 个人信息录入弹窗的ref值
const otherLibraryRef = ref(); // 其他库弹窗的ref值
const roles = ref([]); // 角色权限列表
const editInformation = ref({}); // 点击首页编辑当前行数据
const submissionList = ref([]); // 提交列表
const fileUploadType = ref(new Set(["xlsx"])); // 导入文件类型
const disabledDialog = ref(false); // 弹窗信息禁用
const contentDialogRef = ref(); // 案例库预览弹窗的ref值
const entryPersonLibrary = ref(["talentPool", "video", "lessonPlan", "case"]); // 分公司录入人展示的库id
const auditStatus = ref(""); // 弹窗审核状态
const deleteNodeList = ref(["DRAFT", "END"]); // 当前节点是(拟稿, 已发布)状态 展示删除按钮列表
const messageId = ref(""); // 弹窗信息id

onMounted(() => {
  rolePermissions(); // 获取角色权限
  prefectureInquire(); // 获取首页列表
});
/**
 * 首页新增按钮和导入按钮 展示状态
 */
const newState = () => {
  // 如果是 人才库, 视频库, 教案库, 案例库 根据公司录入人展示; 其他库(文献库) 根据文献录入人展示
  return hasRole(entryPersonLibrary.value.includes(props.libraryTypeId) ? "CITY_ENTERED_BY" : "LITERATURE_ENTERED_BY");
};
/**
 * 角色权限
 */
const rolePermissions = () => {
  roles.value = userStore.user?.roles.map(item => item.roleKey); // 获取角色权限
};
/**
 * 是否有管理角色权限
 * @param item 菜单角色.
 * @returns {boolean} 是否有权限 布尔值
 */
const hasRole = (item) => {
  return roles.value?.includes(item);
};
/**
 * 角色列表中是否有管理角色权限
 * @param roles 角色列表
 */
const hasAnyRole = (roles) => {
  return roles.some((role) => hasRole(role));
};
/**
 * 获取列表
 */
const prefectureInquire = async () => {
  try {
    loading.value = true;
    const { data } = await libraryList(props.libraryTypeId, search.value);
    dataList.value = data.data;
    total.value = data.total;
  } catch (error) {
    throw new Error(error);
  } finally {
    loading.value = false;
  }
};
/**
 * 搜索表单重置
 */
const resetSearchForm = () => {
  proxy.resetForm("searchRef");
  prefectureInquire();
};
/**
 * 新增数据
 */
const addData = () => {
  // 新增打开弹出 数据初始化 除了人才库 其他库新增fileList文件列表
  editInformation.value = props.libraryTypeId === "talentPool" ? {} : { fileList: [] };
  disabledDialog.value = false;
  auditStatus.value = "edit"; // 新增时 弹窗审核状态
  showDialog("addShow");
};
/**
 * 首页列表编辑数据
 * @param value
 * @param type 编辑类型: edit 编辑; view 查看; 处理 handle
 */
const editData = async (value, type) => {
  const { currentNode, id } = value;
  const draftNode = currentNode === "DRAFT"; // 当前节点是拟稿状态
  // 角色为 分公司录入人录入 只有拟稿和草稿可编辑表单信息
  disabledDialog.value = !hasRole("CITY_ENTERED_BY") || (currentNode && !draftNode);
  // 如果当前节点是拟稿状态，并且点击的不是查看 则弹窗审核状态为处理，
  auditStatus.value = draftNode && type !== "view" ? "handle" : type;
  messageId.value = id;
  showDialog("editShow"); // 清空弹窗表单效验
  await getDetailList(id); // 获取详情打开弹出展示
  // 如果是人才库，则打开个人信息弹窗，否则打开其他库弹窗
  setDialogVisible(props.libraryTypeId === "talentPool" ? personageRef.value : otherLibraryRef.value);
};
/**
 * 获取详情
 * @param value 详情id
 */
const getDetailList = async (value) => {
  try {
    proxy.$modal.loading("请稍后...");
    const { data } = await getDetail(props.libraryTypeId, { id: value });
    const { fileList, currentNode, currentOpinion } = data;
    editInformation.value = {
      ...data,
      // 如果没有文件列表, 则赋值空数组
      fileList: fileList || [],
      // 获取到数据 赋值给弹出表单 如果不是拟稿状态, 则处理意见为空 只展示上一环节的处理意见
      currentOpinion: currentNode !== "DRAFT" ? "" : currentOpinion
    };
  } catch (error) {
    ElMessage.error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 弹窗显示
 * @param ref 弹窗ref值
 */
const setDialogVisible = (ref) => {
  ref.dialogVisible = true;
};
/**
 * 预览案例库
 * @param row 当前行数据
 */
const casePreview = async (row) => {
  // 获取到案例库详细内容 打开预览弹窗展示
  await getDetailList(row.id);
  proxy.$refs?.contentDialogRef.show(true);
};
/**
 * 查看/处理按钮状态
 * @param row 当前行数据
 */
const viewProcessing = (row) => {
  const currentHandlerIds = row.currentHandlerId?.split(",");
  // 如果当前工单不是已结束 并且登录人是当前处理人则返回处理按钮，否则返回查看按钮
  return row.currentNode !== "END" && currentHandlerIds?.includes(userStore.userName) ? "处理" : "查看";
};
/**
 * 首页列表弹窗显示
 * @param show 新增弹窗显示: addShow 编辑弹窗显示: editShow
 */
const showDialog = (show) => {
  // 如果是人才库，则打开个人信息弹窗，否则打开其他库弹窗
  props.libraryTypeId === "talentPool" ? personageRef.value[show]() : otherLibraryRef.value[show]();
};
/**
 * 表格多选事件
 * @param value 选择的数据
 */
const handleSelectionChange = (value) => {
  // 获取用户选择数据
  submissionList.value = value;
};
/**
 * 弹窗表单保存并审核
 * @param value 提交的表单信息
 */
const informationSubmit = (value) => {
  saveOrSubmit("submit", value);
};
/**
 * 表单保存事件
 * @param value 保存的表单信息
 */
const informationSave = (value) => {
  saveOrSubmit("save", value);
};
/**
 * 保存并提交事件
 * @param type 提交类型: save 保存; submit 提交;
 * @param value 提交信息
 */
const saveOrSubmit = async (type, value) => {
  try {
    proxy.$modal.loading("请稍后...");
    const submissionType = type === "submit"; // 判断当前是保存还是提交审核
    const action = submissionType ? saveAndSubmit : renewalLibrary;
    await action(props.libraryTypeId, value);
    ElMessage.success(submissionType ? "提交成功" : "保存成功");
    // 关闭人员信息弹窗
    personageRef.value.dialogVisible = false;
    otherLibraryRef.value.dialogVisible = false;
    // 刷新首页列表
    prefectureInquire();
  } catch (error) {
    ElMessage.error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 首页列表删除
 * @param row 当前行
 */
const libraryDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确认删除当前信息?", "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await removeLibrary(props.libraryTypeId, row.id);
    // 刷新首页列表
    prefectureInquire();
    ElMessage.success("删除成功");
  } catch (error) {
    ElMessage.warning("已取消");
  }
};
/**
 * 导入模版下载
 */
const templateDownload = async () => {
  // 导入模版下载
  const data = await downloadTemplate(props.libraryTypeId);
  // 进行blob转换下载
  fileBlobDownload(data, `${exportTemplateName(props.libraryTypeId)}导入模版.xlsx`);
};
/**
 * 导出数据
 */
const derivedData = async () => {
  try {
    proxy.$modal.loading("请稍后...");
    const { userName, title, companyName } = search.value;
    const params = { userName, title, companyName }; // 获取导出所需参数
    const data = await exportTemplate(props.libraryTypeId, params); // 导出模板
    fileBlobDownload(data, `${exportTemplateName(props.libraryTypeId)}.xlsx`); // blob转换 文件下载
  } catch (error) {
    ElMessage.error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 宣讲审核
 * @param data 提交信息
 */
const submitForReview = async (data) => {
  const { value, type } = data; // 获取到提交信息
  await presentationAudit(value, type, data); // 调用审核接口
};
/**
 * 宣讲审核接口封装
 * @param value 提交信息提示
 * @param type 提交类型
 * @param row 当前行
 */
const presentationAudit = async (value, type, row) => {
  try {
    proxy.$modal.loading("请稍后...");
    const { id, currentOpinion } = row;
    const param = [{ id, opinion: currentOpinion }]; // 审核参数
    // 封装审核接口
    const auditProcess = {
      submit: () => reviewSubmit(props.libraryTypeId, param), // 提交审核
      pass: () => passExamination(props.libraryTypeId, param), // 审核通过
      sendBack: () => auditReturn(props.libraryTypeId, param), // 审核退回
    };
    const data = await auditProcess[type]();
    const submitState = data.result === "0";
    ElMessage[submitState ? "error" : "success"](submitState ? data.message : `${value}成功`);
    // 刷新首页列表
    prefectureInquire();
    // 清空首页表单用户选择
    multipleTableRef.value?.clearSelection();
    // 提交成功后清空提交列表 避免提交重复数据
    submissionList.value = [];
    // 关闭人员信息弹窗
    otherLibraryRef.value.dialogVisible = false;
    personageRef.value.dialogVisible = false;
  } catch (error) {
    throw new Error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 首页列表导入
 * @param files 用户上传的附件文件
 */
const handleUploadRequest = async (files) => {
  try {
    const formData = new FormData();
    formData.append("file", files.file); // 文件列表
    const { result, message } = await importTemplate(props.libraryTypeId, formData);
    // 导入失败提示信息
    if(result === "0") {
      ElMessage.error(message);
      return;
    }
    ElMessage.success("导入成功");
    prefectureInquire(); // 获取首页列表
  } catch (error) {
    ElMessage.error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
</script>

<style scoped lang="less">
.dataList {
  .dataList-content {
    //表单查询
    .content-form {
      padding: 16px 52px;
      justify-content: center;
      :deep(.form-body) {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
      }
      .form-btn {
        display: flex;
        justify-content: end;
      }
    }
    // 操作按钮
    .content-form-btn {
      padding: 0px 24px 16px;
      display: flex;
      .content-form-upload {
        margin: 0 10px;
      }
    }
    //表格页面
    .content-table {
      padding: 0 24px;
      .body-form {
        margin-bottom: 16px;
      }
      .table-page {
        display: flex;
        justify-content: end;
      }
    }
  }
}
</style>
